package com.zimmur.service.impl.base;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zimmur.common.ConstData;
import com.zimmur.dao.base.IAdBannerDao;
import com.zimmur.model.base.AdBanner;
import com.zimmur.model.zone.RecommendAd;
import com.zimmur.service.RedisCacheUtil;
import com.zimmur.service.base.IAdBannerService;

@Service("adBannerService")
public class AdBannerServiceImpl implements IAdBannerService {
	private static Logger log=LoggerFactory.getLogger(AdBannerServiceImpl.class);
	
	@Resource
	private IAdBannerDao adBannerDao;
	
	@Resource
	private RedisCacheUtil<AdBanner> stringRedisDao;

	private final String key ="popolook_ad_banner";
	
	private static Object syncLock = new Object();
	
	@Override
	public List<AdBanner> selectAdList(int moduleId) {
		String redis_key = key+"_selectAdList_"+moduleId;
		List<AdBanner> adBannerList=null;
		try {
			//获取 最大值
			boolean isRedis = false;
			try {
				isRedis = stringRedisDao.exists(redis_key);
			} catch (Exception e) {
				log.error(e.getMessage());
			}
			if(isRedis){
				//从缓存中读取
				adBannerList = stringRedisDao.getCacheList(redis_key);
			}else{
				synchronized (syncLock) {
					//二次判断
					try {
						isRedis = stringRedisDao.exists(redis_key);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
					if(isRedis){
						//从缓存中读取
						adBannerList = stringRedisDao.getCacheList(redis_key);
					}else{
						/*缓存中不存在，创建后存入*/
						//从数据库读取
						adBannerList = adBannerDao.selectListByModuleId(moduleId);
						try {
							//存入缓存
							stringRedisDao.setCacheList(redis_key,adBannerList);
							stringRedisDao.setTimeout(redis_key, ConstData.REDIS_KEY_TIMEOUT);
						} catch (Exception e) {
							log.error(e.getMessage());
						}	
					}
				}				
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return adBannerList;
	}

	@Override
	public RecommendAd getRecommendbigAd() {
		return adBannerDao.selectRecommendbigAd();
	}

	@Override
	public List<RecommendAd> getRecommendtwoAd() {
		return adBannerDao.selectRecommendtwoAd();
	}

	@Override
	public List<RecommendAd> getRecommendthreeAd() {
		return adBannerDao.selectRecommendthreeAd();
	}

	@Override
	public AdBanner getBannerByAdId(Integer adId) {
		return adBannerDao.selectBannerByAdId(adId);
	}

	@Override
	public List<RecommendAd> getRecommendTopTwoAd() {
		return adBannerDao.selectRecommendTopTwoAd();
	}
}
